package com.example.ddcoursequery;

import android.util.Log;

import com.app.model.Course;
import com.app.model.Teacher;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by admin on 2015/12/14.
 */
public class HttpData {
    private BasicCookieStore cookieStore;
    private static CloseableHttpClient httpclient;

    public HttpData() {
        cookieStore = new BasicCookieStore();
        httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    }

    public void getTeacherList() {
        try {
            HttpGet httpGet = new HttpGet(Resources.queryTeacherUrl);
            CloseableHttpResponse httpResponse = httpclient.execute(httpGet);

            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream is = httpEntity.getContent();
            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(is));

            Gson gson = new Gson();
            JsonParser parser = new JsonParser();
            JsonArray jsonArray = parser.parse(bufferReader).getAsJsonArray();

            for (JsonElement obj : jsonArray) {
                Teacher teacher = gson.fromJson(obj, Teacher.class);
                Log.i("lyj", teacher.getTeacher_id() + " " + teacher.getTeacher_name());
                AppTeacher appTeacher = new AppTeacher(teacher, false);
                CacheTeacher.teacherList.add(appTeacher);
            }
            httpResponse.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static CloseableHttpClient getInstance() {
        return httpclient;
    }

    public int getCourseList(String teacher_id, String semester) {
        try {
            String url = Resources.queryCourseUrl_is + "teacher_id=" + teacher_id + "&semester=" + semester;
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse httpResponse = httpclient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream is = httpEntity.getContent();
            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(is));
            Gson gson = new Gson();
            JsonParser parser = new JsonParser();
            JsonArray jsonArray = parser.parse(bufferReader).getAsJsonArray();
            Course valCourse = gson.fromJson(jsonArray.get(0), Course.class);
            //Server端没有该老师的数据，需要Server去青果读取
            if ("-1".equals(valCourse.getSemester())) {
                Log.i("lyj","Server端没有该老师的数据，需要Server去青果读取,跳转到验证码界面");
                return -1;
            }else {
                Log.i("lyj","本地有数据，可以跳转");
                Log.i("lyj", "jsonArray.size() = " + jsonArray.size());
                List<AppCourse> appCourseList = new ArrayList<AppCourse>();
                for (JsonElement obj : jsonArray) {
                    Course course = gson.fromJson(obj, Course.class);
                    Log.i("lyj", course.getContent() + " " + course.getSquence());
                    AppCourse appCourse = new AppCourse(course, teacher_id);
                    appCourseList.add(appCourse);
                }
                CacheTeacher.courseList.add(0,appCourseList);
                httpResponse.close();
                return 0;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return -3;
    }

    public String getValidateCodeImg() {

        try {
            String imgpath = Resources.imagePath;
            HttpGet httpGet = new HttpGet(Resources.queryImageUrl);
            CloseableHttpResponse response = httpclient.execute(httpGet);
            HttpEntity httpEntity = response.getEntity();
            InputStream is = httpEntity.getContent();
            FileOutputStream fos = new FileOutputStream(imgpath);
            byte[] buffer = new byte[1024];
            int m = 0;
            while ((m = is.read(buffer)) > -1) {
                fos.write(buffer, 0, m);
            }
            fos.flush();
            fos.close();
            is.close();
            response.close();
            return imgpath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //semester teacher_id code
    public int getCoursesByImageCode(String id, String semester, String imgCodeStr) {
        try {
            String tmpUrl = Resources.queryCourseUrl_isc+"semester="+semester+"&teacher_id="+id+"&code="+imgCodeStr;
            Log.i("lyj","HttpData getCoursesByImageCode "+tmpUrl);
            HttpGet httpGet = new HttpGet(tmpUrl);
            CloseableHttpResponse httpResponse = httpclient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String courseStr = EntityUtils.toString(httpEntity);
            Log.i("lyj","HttpData getCoursesByImageCode content"+courseStr);
            Gson gson = new Gson();
            JsonParser parser = new JsonParser();
            JsonArray jsonArray = parser.parse(courseStr).getAsJsonArray();
            Course valCourse = gson.fromJson(jsonArray.get(0), Course.class);
            //青果端没有该老师的数据，请重新选择老师
            if ("-2".equals(valCourse.getSemester())) {
                Log.i("lyj","青果端没有该老师的数据，请重新选择老师");
                return -2;
            }else {
                Log.i("lyj","服务器返回课程数据");
                Log.i("lyj", "jsonArray.size() = " + jsonArray.size());
                List<AppCourse> appCourseList = new ArrayList<AppCourse>();
                for (JsonElement obj : jsonArray) {
                    Course course = gson.fromJson(obj, Course.class);
                    Log.i("lyj", course.getContent() + " " + course.getSquence());
                    AppCourse appCourse = new AppCourse(course, id);
                    appCourseList.add(appCourse);
                }
                CacheTeacher.courseList.add(0,appCourseList);
                httpResponse.close();
                return 0;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return -2;
    }
}
